const { ccclass, property } = cc._decorator;

@ccclass
export default class CommonFunction {
    // 数组去重复
    static ArrayQuChong(arr) {
        let s1 = new Set(arr);
        return Array.from(s1);
    }
    // static Saijinqu(array, array2) {
    //     for (let index = 0; index < array.length; index++) {
    //         const element = array[index];
    //         if (obj === null || obj === undefined) {
    //             return true;
    //         } else {
    //             return false;
    //         }
    //     }
    // }

    static IsNullOrUndefined(obj) {
        if (obj === null || obj === undefined) {
            return true;
        } else {
            return false;
        }
    }

    // 深拷贝
    static DeepCopy(obj) {
        // 只拷贝对象
        if (typeof obj !== "object") return;
        // 根据obj的类型判断是新建一个数组还是一个对象
        let newObj = obj instanceof Array ? [] : {};
        for (let key in obj) {
            // 遍历obj,并且判断是obj的属性才拷贝
            if (obj.hasOwnProperty(key)) {
                // 判断属性值的类型，如果是对象递归调用深拷贝
                newObj[key] = typeof obj[key] === "object" ? CommonFunction.DeepCopy(obj[key]) : obj[key];
            }
        }
        return newObj;
    }

    // Clone对象
    static Clone(obj): any {
        let ret = { ...obj };
        return ret;
    }

    /**
     * 得到一个节点的世界坐标
     * node的原点在左下边
     * @param {*} node
     */
    static localConvertWorldPoint(node: cc.Node): cc.Vec2 {
        if (node) {
            return node.convertToWorldSpace(cc.v2(0, 0));
        }
        return null;
    }

    // 销毁子物体
    static DestroyAllChildren(parent: cc.Node) {
        for (let i = 0; i <= parent.childrenCount - 1; i++) {
            let child: cc.Node = parent.children[i];
            child.destroy();
        }
    }

    // 设置所有子物体可见或者不可见
    static SetAllChildrenAtive(parent: cc.Node, active: boolean) {
        for (let i = 0; i <= parent.childrenCount - 1; i++) {
            let child: cc.Node = parent.children[i];
            child.active = active;
        }
    }

    static GetFreeChild(parent: cc.Node): cc.Node {
        let c: cc.Node = null;
        for (let i = 0; i <= parent.childrenCount - 1; i++) {
            let child = parent.children[i];
            if (child.active == false) {
                c = child;
                break;
            }
        }

        if (c == null) {
            let node: cc.Node = cc.instantiate(parent.children[0]);
            node.parent = parent;
            node.setPosition(0, 0);
            c = node;
        }

        return c;
    }

    static SetNodeFirstSiblingIndex(_node: cc.Node) {
        _node.setSiblingIndex(0);
    }

    static SetNodeLastSiblingIndex(_node: cc.Node) {
        _node.setSiblingIndex(_node.parent.children.length - 1);
    }

    // 设置父物体，子物体世界坐标不变
    static SetNodeParent(_node: cc.Node, _parent: cc.Node) {
        // const startPst = _parent.convertToNodeSpaceAR(_node.convertToWorldSpaceAR(cc.Vec3.ZERO));
        // _node.parent = _parent;
        // _node.setPosition(startPst);

        // return
        const world_pos = _node.convertToWorldSpaceAR(cc.Vec3.ZERO);
        // console.log(`world_pos`, world_pos.x, world_pos.y);
        _node.setParent(_parent);
        // console.log(`world_pos`, _node.x, _node.y);
        const startPst = _node.parent.convertToNodeSpaceAR(world_pos);
        // _node.setPosition(world_pos);
        _node.position = startPst;
        // console.log(`world_pos`, _node.x, _node.y);

        // const startPst = _node.parent.convertToNodeSpaceAR(world_pos);
        // _node.setPosition(cc.v3(0, 0, 0));
    }

    static GetNodeLocalPostation(_node: cc.Node, _worldPosition_from: cc.Vec3): cc.Vec3 {
        let pos: cc.Vec3 = cc.v3();

        if (_node.parent == null) {
            pos = cc.v3(_node.getPosition());
        } else {
            pos = cc.v3(_node.parent.convertToNodeSpaceAR(_worldPosition_from));
        }
        return pos;
    }

    static GetNodeWorldPostation(_node: cc.Node): cc.Vec3 {
        let pos: cc.Vec3 = cc.v3();
        if (_node.parent == null) {
            pos = cc.v3(_node.getPosition());
        } else {
            pos = cc.v3(_node.parent.convertToWorldSpaceAR(_node.getPosition()));
        }
        return pos;
    }

    // 设置物体世界坐标
    static SetNodeWorldPosition(_node: cc.Node, _worldPosition: cc.Vec3) {
        let pos: cc.Vec3 = cc.v3();

        if (_node.parent == null) {
            pos = _worldPosition;
        } else {
            pos = _node.parent.convertToNodeSpaceAR(_worldPosition);
        }

        _node.setPosition(pos);
    }

    // 延时函数
    static DelayFunction(_callback: Function, _complete: Function, _loop: number = 1, _duration: number = 1) {
        if (_callback) {
            _callback();
        }

        if (_loop <= 1) {
            if (_complete) {
                _complete();
            }
            return;
        }

        let count = 1;
        let callback = function () {
            if (_callback) {
                _callback();
            }

            if (count >= _loop - 1) {
                // GameManager.Instance.unschedule(callback);

                if (_complete) {
                    _complete();
                }
            }

            count++;
        };
        // GameManager.Instance.schedule(callback, _duration);
    }

    // 将时间转换为"00:00"格式
    static FormatTime(time) {
        let minute: any = Math.floor(time / 60) % 60;
        let second: any = time % 60;

        if (minute.toString().length <= 1) {
            minute = "0" + minute.toString();
        }
        if (second.toString().length <= 1) {
            second = "0" + second.toString();
        }

        return minute + ":" + second;
    }

    // 比较两个数组是否相等
    static CompareArray(_array1: any, _array2: any) {
        let isSame: boolean = false;

        if (_array1.length != _array2.length) {
            return false;
        }

        let count = 0;
        for (let index = 0; index < _array1.length; index++) {
            const element1 = _array1[index];
            const element2 = _array2[index];
            if (element1 === element2) {
                count++;
            }
        }

        if (count === _array1.length) {
            isSame = true;
        }

        return isSame;
    }

    static Indexof(array, obj) {
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            if (obj === element) {
                return index;
            }
        }
        return -1;
    }

    // 有#的情况
    static GetQueryStringhash(key) {
        let after = window.location.search;
        if (after.indexOf("?") === -1) return null; // 如果url中没有传参直接返回空
        // key存在先通过search取值如果取不到就通过hash来取
        after = after.substr(1) || window.location.hash.split("?")[1];
        if (after) {
            let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
            let r = after.match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            } else {
                return null;
            }
        }
    }

    // 没有#情况
    static GetQueryString() {
        let data = {};
        let src = window.location.href;
        let index = src.indexOf("?");
        if (index === -1) {
            return data;
        }
        let dataStr = src.substring(src.indexOf("?") + 1);
        let dataArray = dataStr.split("&");
        dataArray.forEach((str) => {
            let param = str.split("=");
            data[param[0]] = param[1];
        });
        return data;
    }

    // 获取itemdata
    static Get_itemdata(_list, _param, _value) {
        // let id = _level - 1;

        let arr = _list.filter((item) => {
            return item[_param] == _value;
        });

        // let item = SheepCommonData[id];
        return arr[0];
    }

    static NumberFormat(_param) {
        // let str: string[] = [`万`, `亿`, `兆`, `京`, `垓`,];
        let value: string = "";

        let level = 10000;
        let sizesValue = "";
        let isGe: boolean = false;

        // 判断取哪个单位
        if (_param < Math.pow(10, 4)) {
            level = 1;
            sizesValue = "";
            isGe = true;
        } else if (_param >= Math.pow(10, 4) && _param < Math.pow(10, 8)) {
            level = Math.pow(10, 4);
            sizesValue = "万";
        } else if (_param >= Math.pow(10, 8) && _param < Math.pow(10, 12)) {
            level = Math.pow(10, 8);
            sizesValue = "亿";
        } else if (_param >= Math.pow(10, 12) && _param < Math.pow(10, 16)) {
            level = Math.pow(10, 12);
            sizesValue = "兆";
        } else if (_param >= Math.pow(10, 16) && _param < Math.pow(10, 20)) {
            level = Math.pow(10, 16);
            sizesValue = "京";
        } else if (_param >= Math.pow(10, 20)) {
            level = Math.pow(10, 20);
            sizesValue = "垓";
        }

        let num = _param / level;
        let result: number = Math.floor(num * 100) / 100;
        if (isGe) {
            result = Math.floor(result);
        }
        value = result + sizesValue;

        return value;
    }

    // --哈希颜色转RGB颜色
    static Hex2color(hexColor) {
        const hex = hexColor.replace(/^#?/, "0x");
        const c = parseInt(hex);
        const r = c >> 16;
        const g = (65280 & c) >> 8;
        const b = 255 & c;

        return cc.color(r, g, b, 255);

        // 样例
        // headNode.color = hex2color("#F1F1F1");
    }

    static checkIntersectOrContain(nodeA: cc.Node, nodeB: cc.Node) {
        const boundingBoxA = nodeA.getBoundingBoxToWorld();
        const boundingBoxB = nodeB.getBoundingBoxToWorld();
        const intersect = boundingBoxA.intersects(boundingBoxB);
        const AcontainB = boundingBoxA.containsRect(boundingBoxB);
        const BcontainA = boundingBoxB.containsRect(boundingBoxA);
        return intersect || AcontainB || BcontainA;
    }

    static checkIntersectOrContainByBoundingBox(boundingBoxA: cc.Rect, boundingBoxB: cc.Rect) {
        const intersect = boundingBoxA.intersects(boundingBoxB);
        const AcontainB = boundingBoxA.containsRect(boundingBoxB);
        const BcontainA = boundingBoxB.containsRect(boundingBoxA);
        return intersect || AcontainB || BcontainA;
    }

    static saveJSON(data, filename) {
        if (!data) {
            alert('data is null');
            return;
        }
        if (!filename) {
            filename = 'json.json'
        }
        if (typeof data === 'object') {
            data = JSON.stringify(data, undefined, 4)
        }
        // 文件保存
        let blob = new Blob([data], { type: 'text/json' });
        let e = document.createEvent('MouseEvents');
        let a = document.createElement('a');
        a.download = filename;
        a.href = window.URL.createObjectURL(blob);
        a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        a.dispatchEvent(e);
    }

}

/**map */
const tempV2 = cc.v2();
/**返回子节点在父节点中的坐标 */
export function ConvertPosition(child: cc.Node, parent: cc.Node, out?: cc.Vec2): cc.Vec2 {
    const out0 = out ? out : cc.v2();
    child.convertToWorldSpaceAR(cc.Vec2.ZERO, tempV2);
    parent.convertToNodeSpaceAR(tempV2, out0);
    return out0;
}


/** 调试 */
window["CommonFunction"] = CommonFunction;
